package com.xhb.ui.download;

import com.xhb.biz.config.APPConfig;
import com.xhb.biz.constant.DownloadConstant;
import com.xhb.biz.po.DownloadPO;
import com.xhb.biz.service.DownloadFileService;
import com.xhb.ui.ToolBar;
import com.xhb.ui.resources.Resources;
import com.xhb.ui.tools.UItools;
import lombok.Data;
import org.noear.solon.Solon;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;

/**
 * 一个文件下载面板
 */
@Data
public class DownloadFilePanel extends JPanel implements Runnable {
    private DownloadPO downloadPO;

    private JLabel status;

    private JProgressBar progressBar;

    private boolean isRun;

    public DownloadFilePanel(DownloadPO downloadPO) {
        this.downloadPO = downloadPO;
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setVisible(true);
        add(fileContent());
        add(pupMenu());
        if (downloadPO.getStatus() == DownloadConstant.STATUS_ING) {
            isRun = true;
            new Thread(this).start();
        }
    }

    /**
     * 更多菜单
     *
     * @return
     */
    public JButton pupMenu() {
        JButton pop = new JButton();
        UItools.parseButton(pop);
        pop.add(createMenuButton(), BorderLayout.NORTH);
        Border border = new MatteBorder(0, 0, 0, 1, Color.LIGHT_GRAY);
        setBorder(border);
        return pop;
    }

    public JPanel fileContent() {
        JPanel filePanel = new JPanel();

        filePanel.setLayout(new BorderLayout());
        //手动设置组建的大小
        Dimension dimension = new Dimension();
        dimension.setSize(200,30);
        filePanel.setPreferredSize(dimension);

        JLabel fileName = new JLabel();
        fileName.setText(downloadPO.getFileName());
        filePanel.add(fileName, BorderLayout.NORTH);
        status = new JLabel();
        status.setText(downloadPO.getStatusName());
        filePanel.add(status, BorderLayout.CENTER);

        progressBar = new JProgressBar();
        progressBar.setValue(downloadPO.getProgress());
        filePanel.add(progressBar, BorderLayout.SOUTH);
        parseStatus();
        return filePanel;
    }

    public void parseStatus() {
        progressBar.setValue(downloadPO.getProgressBar());
        status.setText(downloadPO.getStatusName());
        //如果正在下载的话，显示下载进度条
        if (downloadPO.getStatus() == DownloadConstant.STATUS_ING) {
            progressBar.setVisible(true);
            status.setVisible(false);
        } else {
            progressBar.setVisible(false);
            status.setVisible(true);
        }
    }

    @Override
    public void run() {
        while (isRun && BottomDownloadBar.getInstance().getVisiable() && downloadPO.getStatus() == DownloadConstant.STATUS_ING) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //历史记录
            Solon.context().getBeanAsync(DownloadFileService.class, bean -> {
                downloadPO = bean.getById(this.downloadPO.getId());
                parseStatus();
            });
        }
    }

    public void dispose() {
        this.isRun = false;
    }


    private JComponent createMenuButton() {
        final JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.setName(downloadPO.getId());

        final ToolBar.ActionButton button = new ToolBar.ActionButton("Preferences", null);
        button.setIcon(Resources.getIcon("up.png"));
        //添加弹出菜单侦听器
        popupMenu.addPopupMenuListener(new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                button.setIcon(Resources.getIcon("up.png"));
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                button.setIcon(Resources.getIcon("down.png"));
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {

            }
        });
        button.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                popupMenu.removeAll();
                if(downloadPO.getStatus() == DownloadConstant.STATUS_CANCELLED){
                    //取消文件禁用按钮
                    popupMenu.add(resumeMenuItem()).setEnabled(false);
                    popupMenu.add(selectMenuItem()).setEnabled(false);
                    popupMenu.addSeparator();
                    popupMenu.add(cancelMenuItem()).setEnabled(false);
                }else if(downloadPO.getStatus() == DownloadConstant.STATUS_COMPLETE){
                    popupMenu.add(selectMenuItem());
                    popupMenu.addSeparator();
                    popupMenu.add(cancelMenuItem()).setEnabled(false);
                }else {
                    if (downloadPO.getStatus() == DownloadConstant.STATUS_ING) {
                        popupMenu.add(pausedMenuItem());
                    } else {
                        popupMenu.add(resumeMenuItem());
                    }
                    popupMenu.add(selectMenuItem());
                    popupMenu.addSeparator();
                    popupMenu.add(cancelMenuItem());
                }

                if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                    popupMenu.show(e.getComponent(), 0, -90);
                } else {
                    popupMenu.setVisible(false);
                }
            }
        });
        return button;
    }

    private JMenuItem pausedMenuItem() {
        JMenuItem menuItem = new JMenuItem("暂停");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DownloadManager.getInstance().paused(downloadPO.getId());
            }
        });
        return menuItem;
    }

    private JMenuItem resumeMenuItem() {
        JMenuItem menuItem = new JMenuItem("继续");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DownloadManager.getInstance().resume(downloadPO.getId());
            }
        });
        return menuItem;
    }

    private JMenuItem selectMenuItem() {
        JMenuItem menuItem = new JMenuItem("在文件夹中显示");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    Desktop.getDesktop().open(new File(APPConfig.downloadPath));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        return menuItem;
    }

    private JMenuItem cancelMenuItem() {
        JMenuItem menuItem = new JMenuItem("取消");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DownloadManager.getInstance().cancel(downloadPO.getId());
            }
        });
        return menuItem;
    }
}
